<template>
  <div>
    <navigation-bar customTitle="我的下载">
      <div class="searchContent">
        &nbsp;
        <!-- <el-input
          v-model="elementName"
          placeholder="请输入元件名称"
          size="mini"
          style="width: 150px; margin-right: 10px"
        ></el-input>
        <el-select
          v-model="version"
          clearable
          placeholder="请选择版本"
          size="mini"
          style="width: 150px; margin-right: 10px"
        >
          <el-option
            v-for="item in versionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            width="150px"
          >
          </el-option>
        </el-select>
        <custom-button
          type="search"
          style="margin-right: 10px"
          @searchClick="searchClick"
        ></custom-button>
        <custom-button
          type="reset"
          style="margin-right: 10px"
          @resetClick="resetClick"
        ></custom-button> -->
      </div>
    </navigation-bar>
    <tableHeightIndex
      :dataSource="dataSource"
      :tableColumns="tableColumns"
      :btnList="btnList"
      :pageSize="pageSize"
      :pageCount="pageCount"
      :pageNo="pageNo"
      btnListWidth="70"
      @downloadRow="downloadRow"
      :height="secondTableHeight"
    ></tableHeightIndex>

    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <form-index
          :formConfig="formConfig"
          @submit="submit"
          :type="type"
          @formInputChange="formInputChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="showPwdJudge">
      <pwdJudge @close="showPwdJudge = false" @success="startDown"></pwdJudge>
    </div>
  </div>
</template>

<script>
import { tagManageForm } from "@/assets/form/managementCenter/tagManageForm";
import customDialog from "@/components/customComponents/customDialog";
// import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
// import tableIndex from "@/components/customComponents/customeTable/tableIndex";
import tableHeightIndex from "@/components/customComponents/customeTable/tableHeightIndex.vue";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon, ImageAddress } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
import { Utility } from "@/libs/utility";
import pwdJudge from "@/components/customComponents/pwdJudge";
export default {
  components: {
    navigationBar,
    // customButton,
    // tableIndex,
    customDialog,
    formIndex,
    tableHeightIndex,
    pwdJudge,
  },
  data() {
    return {
      showPwdJudge: false,
      currentSelectDown: {}, // 存储当前点击的那行数据
      secondTableHeight: document.body.clientHeight - 143,
      version: "",
      versionList: [
        {
          value: "1",
          label: "版本1",
        },
        {
          value: "2",
          label: "版本2",
        },
      ],
      selectItem: [],
      elementName: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "name",
          label: "元件名称",
        },
        {
          prop: "updateTime",
          label: "上传时间",
        },
        {
          prop: "username",
          label: "上传人",
        },
      ],
      btnList: ["download"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: tagManageForm,
      type: "add",
    };
  },
  methods: {
    stringToArrayBuffer(str) {
      console.log(str, "str....................");
      var buf = new ArrayBuffer(str.length);
      var bufView = new Uint8Array(buf);
      for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    },
    startDown() {
      this.showPwdJudge = false;
      const item = this.currentSelectDown;
      var id = item.Id;
      var name = item.FamilyName;
      AjaxCommon("/api/familyresouce/downloadfile/" + id, "getBlob", null).then(
        (res) => {
          if (res?.status == 200) {
            Utility.oprRecord(3, id);
            // var data = self.stringToArrayBuffer(res.data);
            var blob = new Blob([res.data]);
            const href = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.download = name;
            link.href = href;
            link.click();
            try {
              document.body.removeChild(link);
            } catch (error) {
              console.log(error.message);
            }
            URL.revokeObjectURL(href); // 释放内存
          } else {
            PopupCommon.notify("error", res?.data?.msg);
          }
        }
      );
    },
    downloadRow(d) {
      this.currentSelectDown = d.data;
      this.showPwdJudge = true;
    },
    // 调用收藏
    async initSc() {
      const res = await AjaxCommon(`/api/favorite/getfavoritefamilys`, "get");
      var data = res.data.response;
      if (data && data.length > 0) {
        return data;
      }
      return [];
    },
    async initTable() {
      var index = 3;
      const scList = await this.initSc();
      var imageAddress = ImageAddress;
      console.log(index);
      var params = `?Type=${index}&count=100`;
      AjaxCommon(
        "/api/FamilyFileOprateController/GetFamilyResouceByOprate" + params,
        "get",
        null
      ).then((res) => {
        console.log(res, params);
        var data = res.data.response;
        if (data && data.length > 0) {
          self.imgList = [];
          self.imgIndex = 0;
          data.map((t) => {
            t.id = t.Id;
            t.imgSrc = imageAddress + "/" + t.PreImage;
            t.name = t.FamilyName;
            t.show = false;
            t.username = t.UploadUser;
            t.updateTime = t.UploadTime;
            t.isSc =
              scList.length > 0 &&
              scList.filter((cc) => cc.Id == t.Id).length > 0
                ? 1
                : 0;
            t.gs = "rfa";
            t.bb = "版本1";

            var imgList = t.MulViewImages;
            var newImgList = [];
            if (imgList) {
              imgList = JSON.parse(imgList);
              if (imgList && imgList.length > 0) {
                imgList.map((b) => {
                  b = imageAddress + "/" + b;
                  newImgList.push(b);
                  return b;
                });
              }
              console.log(imgList, "imgList.....");
              t.MulViewImages = newImgList;
            } else {
              t.MulViewImages = [];
            }
            return t;
          });
        }
        this.dataSource = data;
      });
    },
    handleSelectionChange(d) {
      this.selectItem = d;
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    submit(d) {
      console.log(d);
      // let self = this
      // console.log(d)
      // if (d.id) {
      // 	AjaxCommon("/ccdc/cfg/device/device/edit", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 				this.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // } else {
      // 	delete d.id
      // 	AjaxCommon("/ccdc/cfg/device/device/add", "post", d)
      // 		.then((res) => {
      // 			if (res.data.code == 200) {
      // 				PopupCommon.notify("success", "操作成功")
      // 				self.initPage()
      // 				self.dialogClose()
      // 			} else {
      // 				PopupCommon.notify("error", res.data.message)
      // 			}
      // 		})
      // 		.catch((err) => {
      // 			PopupCommon.notify("error", err.message)
      // 		})
      // }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.elementName = "";
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    editRow(d) {
      this.type = "edit";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "编辑" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    deleteRow(d) {
      console.log(d);
      const id = d.data.id;
      let self = this;
      AjaxCommon("/ccdc/cfg/device/device/delete?id=" + id, "delete", {
        optReason: d.optReason,
      }).then((res) => {
        console.log(res, "res...............");
        if (res.data.code == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
          self.dialogClose();
        } else {
          PopupCommon.notify("error", res.data.message);
        }
      });
    },
    // 初始化事件
    initPage() {
      this.initTable();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initPage();
    });
  },
};
</script>

<style>
.elementFBZ {
  background-color: #ebf4fe;
  border-radius: 6px;
  color: #439efe !important;
  padding: 5px 10px;
  font-size: 14px;
}

.elementYFB {
  background-color: #eff8ea;
  border-radius: 6px;
  color: #6ac25c !important;
  padding: 5px 10px;
  font-size: 14px;
}

.elementDFB {
  background-color: #f3f3f4;
  border-radius: 6px;
  color: #9897a8 !important;
  padding: 5px 10px;
  font-size: 14px;
}
</style>
